(function () {


    "use strict";

    var URL2 = {
        service: {
            getServiceType: "/rest/servtype/getServType?"
        },
        servreq: {
            getServReq: "/rest/servreq/getServReq?",
            getServReqs: "/rest/servreq/getServReqs?",
            getServReqsCount: "/rest/servreq/getServReqsCount?",
            getSummary: "/rest/servreq/getSummary?",
            createServReq: "/rest/servreq/createServReq?",
            setCancelled: "/rest/servreq/setCancelled?",
            setInitial: "/rest/servreq/setInitial?",
            pay: "/rest/servreq/pay?",
            setPaid: "/rest/servreq/setPaid?"
        },
        patient: {
            getPatients: "/rest/patient/getPatients?",
            getPatient: "/rest/patient/getPatient?",
            getPatientPackage: "/rest/patient/getPatientPackage?",
            getPatientsCount: "/rest/patient/getPatientsCount?",
            sharePatient: "/rest/chat/createChatMessageSharingPatient?"
        },
        user: {
            getUsers: "/rest/user/getUsers?userRole={0}&like={1}&pageNo={2}&pageSize={3}",
            getUserById: "/rest/user/getUserById?userId={0}"
        },
        diseaseType: {
            getDiseaseType: "/rest/diseasetype/getDiseaseTypeList?"
        }
    };

    app.controller("ServiceIndexCtrl", ["$scope", "$modal", "$timeout", "RESTService", "ModeShapeService", "AuthService", "$stateParams", "$translate",
        function ($scope, $modal, $timeout, RESTService, ModeShapeService, AuthService, $stateParams, $translate) {

            $scope.service_Id = $stateParams.service_Id;
            $scope.summary = "";

            $scope.status = $stateParams.status;
            if ($scope.status == null || $scope.status == "") {
                $scope.status = "all"; // status:all,supplied,inprogress,finished
            }
            $scope.like = "";
            $scope.page = {
                totalItems: 0,
                currentPage: 1,
                currentItems: 0,
                maxSize: 5,				//max size of pagination
                itemsPerPage: 10
            };
            $scope.setPage = function (pageNo) {
                $scope.page.currentPage = pageNo;
            };

            // get service type
            console.log();
            RESTService.getResponse(URL2.service.getServiceType + "service_Id=" + $scope.service_Id).then(function (response) {
                $scope.serviceType = response[0];
                $scope.serviceTypeName = $translate.instant('servicetype.servicetype_' + $scope.serviceType.service_Id);
            });

            // get service summary
            RESTService.getResponse(URL2.servreq.getSummary + "service_Id=" + $scope.service_Id).then(function (response) {
                $scope.summary = response[0];
            });

            $scope.pageChanged = function () {
                loadListData();
            };

            $scope.$watch('like', function (newValue) {
                if (newValue == '') {
                    loadListData();
                }
            });

            $scope.setStatus = function (newStatus) {
                $scope.status = newStatus;
                loadListData();
            };

            $scope.servReqs = [];
            var loadListData = function () {
                RESTService.getResponse(URL2.servreq.getServReqsCount + "service_Id=" + $scope.service_Id +
                    "&status=" + $scope.status + "&like=" + $scope.like).then(function (response) {
                    $scope.page.totalItems = response[0].count;
                });
                RESTService.getResponse(URL2.servreq.getServReqs + "service_Id=" + $scope.service_Id +
                    "&status=" + $scope.status + "&like=" + $scope.like
                    + "&pageNo=" + $scope.page.currentPage + "&pageSize=" + $scope.page.itemsPerPage)
                    .then(function (response) {
                        $scope.servReqs = response;
                        $scope.page.currentItems = $scope.servReqs.length;
                    });
            }
            $scope.init = function () {
                loadListData();
            }

            $scope.onSetStatus = function ($event, status, patientId, input) {
                switch (status) {
                    case "NeedOpe":
                        input = $.param(angular.extend({
                            diag_SpinalCord: "",
                            diseaseType: "",
                            diag_Calcify: "",
                            diag_Slip: "",
                            diag_Desc: ""
                        }, input));
                        break;
                    case "NoOpeNeeded":
                        input = $.param(angular.extend({
                            diag_Desc: ""
                        }, input));
                        break;
                    default:
                }

                $($event.currentTarget).button("loading");
                RESTService.getResponse(URL2.patient["set" + status].format(patientId, input)).then(
                    function () {
                        rowCountInstance(function () {
                            $scope.dtInstance.DataTable().ajax.reload();
                            modelInstance && modelInstance.close();
                            modelInstance1 && modelInstance1.close();
                        });
                        $($event.currentTarget).button("reset");
                    });
            };


            //3 open modal
            $scope.open = function (attrs, model) {
                // model.scope = $scope;
                var modalInstance = $modal.open(angular.extend({
                    backdrop: "static",
                    controller: "ModalInstanceCtrl",
                    resolve: {
                        items: function () {
                            return [Object(model)];
                        }
                    },
                    scope: $scope
                }, attrs));
            };

            // open Cancelled modal
            $scope.openCancelled = function (attrs, model) {
                $scope.servReq_Id = model.servReq_Id;
                //model.scope = $scope;
                var modalInstance = $modal.open(angular.extend({
                    backdrop: "static",
                    controller: "ModalInstanceCtrl",
                    resolve: {
                        items: function () {
                            return [Object(model)];
                        }
                    }
                }, attrs));

                // receieve the specialist data from modal window
                modalInstance.result.then(function () {
                    // get user
                    RESTService.postResponse(URL2.servreq.setCancelled, {servReq_Id: $scope.servReq_Id}).then(
                        function (response) {
                            // reload data
                            loadListData();
                        });
                }, function () {
                });
            };

            // open setInitial modal
            $scope.openSetInitial = function (attrs, model) {
                $scope.servReq_Id = model.servReq_Id;
                //model.scope = $scope;
                var modalInstance = $modal.open(angular.extend({
                    backdrop: "static",
                    controller: "ModalInstanceCtrl",
                    resolve: {
                        items: function () {
                            return [Object(model)];
                        }
                    }
                }, attrs));

                // receieve the specialist data from modal window
                modalInstance.result.then(function () {
                    // click ok, then call setInitial(servReq_Id)
                    RESTService.postResponse(URL2.servreq.setInitial, {servReq_Id: $scope.servReq_Id}).then(
                        function (response) {
                            // reload data
                            loadListData();
                        });
                }, function () {
                });
            };

            // share case
            $scope.sharePatient = function (a, b) {
                var patient_Id = a.patient_Id ? a.patient_Id : a.patient_Id2;
                var params = {
                    patient_Id: patient_Id
                    , friendId: b
                }
                console.log(params);
                RESTService.postResponse(URL2.patient.sharePatient, params).then(
                    function (suc) {
                        console.log(suc);
                    });
            }
        }]);

    app.controller("SelectPatientCtrl", ["$scope", "$modal", "$timeout", "RESTService", "ModeShapeService", "AuthService", "$stateParams", "$translate",
        function ($scope, $modal, $timeout, RESTService, ModeShapeService, AuthService, $stateParams, $translate) {

            $scope.service_Id = $stateParams.service_Id;

            $scope.status = "all"; // status:all,supplied,inprogress,finished
            $scope.like = "";
            $scope.page = {
                totalItems: 0,
                currentPage: 1,
                currentItems: 0,
                maxSize: 5,				//max size of pagination
                itemsPerPage: 10
            };
            $scope.setPage = function (pageNo) {
                $scope.page.currentPage = pageNo;
            };

            var loadSelectListData = function () {
                RESTService.getResponse(URL2.patient.getPatientsCount + "status=" + $scope.status + "&like=" + $scope.like).then(
                    function (response) {
                        $scope.page.totalItems = response[0].count;
                    });
                RESTService.getResponse(URL2.patient.getPatients + "status=" + $scope.status + "&like=" + $scope.like
                    + "&pageNo=" + $scope.page.currentPage + "&pageSize=" + $scope.page.itemsPerPage)
                    .then(function (response) {
                        $scope.patients = response;
                        $scope.page.currentItems = $scope.patients.length;

                    })
            };

            $scope.pageChanged = function () {
                loadSelectListData();
            };

            $scope.searchPatient = function () {
                loadSelectListData();
            };

            // get service type
            RESTService.getResponse(URL2.service.getServiceType + "service_Id=" + $scope.service_Id).then(function (response) {
                $scope.serviceType = response[0];
                $scope.serviceTypeName = $translate.instant('servicetype.servicetype_' + $scope.serviceType.service_Id);
            });

            $scope.init = function () {
                loadSelectListData();
            };

            //3 open modal
            $scope.open = function (attrs, model) {
                //model.scope = $scope;
                var modalInstance = $modal.open(angular.extend({
                    backdrop: "static",
                    controller: "ModalInstanceCtrl",
                    resolve: {
                        items: function () {
                            return [Object(model)];
                        }
                    }
                }, attrs));
            };

        }]);

    app.controller("pureDetailsCtrl", ["$scope", "$modal", "$timeout", "RESTService", "ModeShapeService", "AuthService", "$stateParams", "$state",
        function ($scope, $modal, $timeout, RESTService, ModeShapeService, AuthService, $stateParams, $state) {

            $scope.service_Id = $stateParams.service_Id;
            $scope.patient_Id = $stateParams.patient_Id;
            $scope.chosen_Expert = "";
            $scope.chosen_Expert_Id = "";


            var loadPureDetailPageListData = function () {
                RESTService.getResponse(URL2.service.getServiceType + "service_Id=" + $scope.service_Id)
                    .then(function (response) {
                        $scope.serviceType = response[0];
                    });
                RESTService.getResponse(URL2.patient.getPatient + "patient_Id=" + $scope.patient_Id)
                    .then(function (response) {
                        $scope.patient = response;
                    });
                RESTService.getResponse(URL2.patient.getPatientPackage + "patient_Id=" + $scope.patient_Id)
                    .then(function (response) {
                        $scope.patientPackage = response[0];
                    });
                RESTService.getResponse(URL2.user.getUsers.format("Specialist", "", 1, 1000)).then(
                    function (response) {
                        $scope.specialists = response;
                    });

            };
            $scope.init = function () {
                loadPureDetailPageListData();
            };

            // specialist list initial
            var loadSpecialistData = function () {
                RESTService.getResponse(URL2.user.getUsers.format("Specialist", "", 1, 1000)).then(
                    function (response) {
                        $scope.specialists = response;
                    });
            };
            $scope.initSpecialist = function () {
                loadSpecialistData();
            };

            // open normal modal
            $scope.open = function (attrs, model) {
                //model.scope = $scope;
                var modalInstance = $modal.open(angular.extend({
                    backdrop: "static",
                    controller: "ModalInstanceCtrl",
                    resolve: {
                        items: function () {
                            return [Object(model)];
                        }
                    }
                }, attrs));
            };

            // open specialist modal
            $scope.openSpecialist = function (attrs, model) {
                //model.scope = $scope;
                var modalInstance = $modal.open(angular.extend({
                    backdrop: "static",
                    controller: "SpecialistModalInstanceCtrl",
                    scope: $scope,
                    resolve: {
                        items: function () {
                            return [Object(model)];
                        }
                    }
                }, attrs));

                // receive the specialist data from modal window
                modalInstance.result.then(
                    function (userId) {
                        // get user
                        if(userId == undefined){
                            return;
                        }
                        RESTService.getResponse(URL2.user.getUserById.format(userId)).then(
                            function (response) {
                                $scope.chosen_Expert = response[0];
                                if ($scope.chosen_Expert != null) {
                                    $scope.chosen_Expert_Id = $scope.chosen_Expert.userId;
                                }
                            });
                    }, function () {
                    });
            };

            $scope.clear = function () {
                $scope.chosen_Expert.realName = "";
            };

            // create a new service request
            $scope.createServReq = function () {
                // success, to ui-sref="app.process.pay({ service_Id:service_Id })"
                RESTService.postResponse(URL2.servreq.createServReq, {
                    service_Id: $scope.service_Id,
                    patient_Id: $scope.patient_Id,
                    user_Id: $scope.chosen_Expert_Id
                })
                    .then(function (response) {
                        if (response[0] != null) {
                            var servReq_Id = response[0].servReq_Id;
                            // success, redirect
                            $state.go("app.process.pay", {"servReq_Id": servReq_Id});
                        }
                    });
            }

        }]);

    app.controller("SpecialistModalInstanceCtrl",
        function ($scope, RESTService, $modalInstance) {

            $scope.specialists = "";

            var loadData = function () {
                RESTService.getResponse(URL2.user.getUsers.format("Specialist", "", 1, 1000)).then(
                    function (response) {
                        $scope.specialists = response;
                    });
            };

            $scope.initSpecialist = function () {
                loadData();
            };

            $scope.setSpecialist = function (userId) {
                // $scope.cancel();
                $modalInstance.close(userId);
            };

            $scope.cancel = function () {
                console.log($modalInstance);
                // $modalInstance.dismiss();
                $modalInstance.close();
            }

        });


    app.controller("ServReqPayCtrl", ["$scope", "$modal", "$timeout", "RESTService", "ModeShapeService", "AuthService", "$stateParams", "$state",
        function ($scope, $modal, $timeout, RESTService, ModeShapeService, AuthService, $stateParams, $state) {

            $scope.servReq_Id = $stateParams.servReq_Id;
            $scope.servReq = "";
            $scope.service_Id = "";

            var loadData = function () {
                RESTService.postResponse(URL2.servreq.getServReq, {servReq_Id: $scope.servReq_Id}).then(
                    function (response) {
                        $scope.servReq = response[0];
                    });

            };
            $scope.init = function () {
                loadData();
            };

            //3 open modal
            $scope.open = function (attrs, model) {
                //model.scope = $scope;
                $scope.service_Id = model.service_Type;
                var modalInstance = $modal.open(angular.extend({
                    backdrop: "static",
                    controller: "PayModalInstanceCtrl",
                    resolve: {
                        items: function () {
                            return [Object(model)];
                        }
                    }
                }, attrs));

                // receive the result, and response
                modalInstance.result.then(function (data) {
                    if (data == 1) {
                        $state.go("app.process.service", {"service_Id": $scope.service_Id});
                    }
                }, function () {
                });

            };

        }]);

    app.controller("PayModalInstanceCtrl",
        function ($scope, RESTService, AuthService, $modalInstance, items, $interval, $timeout) {
            $scope.canClose = true; // can show button 'close'
            $scope.wechatPayUrl = "";
            $scope.test = "";
            $scope.servReq = items[0];
            $scope.servReq_Id = items[0].servReq_Id;
            $scope.canGo = false; // can show button 'go'
            $scope.canSetPaid = true; // can show span 'setPaid'

            $scope.init = function (payMethod) {
                if (payMethod == 'Alipay') {
                    $timeout(function () {
                        var ip = AuthService.getRsContext();
                        window.open('./views/work/Alipay.html?servReq_Id=' + $scope.servReq_Id + '&access_token=' + access_token + '&ip=' + ip, "_blank", 'width=1100,height=650');
                    }, 500);
                }
                if (payMethod == 'Wechat') {
                    var getData = function () {
                        var params = {
                            servReq_Id: $scope.servReq_Id,
                            type: payMethod
                        };
                        // var newWin = window.open("","_blank",'width=1100,height=650');
                        // console.log('payUrl:',payUrl);
                        // RESTService.postResponse(URL2.servreq.pay, params).then(
                        RESTService.postResponse(URL2.servreq.pay, params, true).then(
                            function (response) {
                                var code = response.code;
                                if (code == null) {
                                    $scope.wechatPayUrl = response;
                                } else {
                                    $scope.wechatPayUrl = "images/servreq_pay_" + code + ".jpg";
                                }
                            });
                        $scope.canReloadQr = true;// can show button 'reload Qr'
                    };
                    getData();

                    $scope.refreshQr = function () {
                        $scope.wechatPayUrl = "";
                        $scope.canReloadQr = true;
                        getData();
                    };
                }


                var status = "waitpaid";
                // execute check timer
                var timer = $interval(function () {
                    if (status == "waitpaid") {
                        RESTService.postResponse(URL2.servreq.getServReq, {servReq_Id: $scope.servReq_Id}).then(function (response) {
                            if (response[0] != null) {
                                status = response[0].status;
                                if (status != "waitpaid") {
                                    $scope.canSetPaid = false;
                                    $scope.canClose = false;
                                    $scope.canGo = true;
                                    $scope.canReloadQr = false;
                                }
                                // paid successfully
                                if (status == "initial") {
                                    $scope.wechatPayUrl = "images/servreq_pay_0.jpg";
                                }
                                // be cancelled
                                if (status == "cancelled") {
                                    $scope.wechatPayUrl = "images/servreq_pay_4711.jpg";
                                }
                            }
                        });
                    }
                }, 3000);

                $scope.cancel = function () {
                    $modalInstance.close();
                    $interval.cancel(timer);
                }

                $scope.ok = function () {
                    $modalInstance.close(1);
                    $interval.cancel(timer);
                }
            };

            $scope.setPaid = function () {
                RESTService.postResponse(URL2.servreq.setPaid, {servReq_Id: $scope.servReq_Id}, true).then(
                    function (response) {
                        if (response.code != null) {
                            if (response.code == 0) {
                                $scope.canSetPaid = false;
                                $scope.canClose = false;
                                $scope.canGo = true;
                                $scope.canReloadQr = false;
                                $scope.wechatPayUrl = "images/servreq_pay_0.jpg";
                            }
                        }
                    });
            }
        });

    // app.controller("UserDetailCtrl", ["$scope", "RESTService",
    //     function ($scope, RESTService) {
    //         $scope.user = angular.extend({}, $scope.selected.item);
    //
    //         $scope.activityList = [];
    //
    //         if ($scope.user._doctor == null) {
    //             $scope.user._doctor = {
    //                 userId: '',
    //                 doctQuali_Id: '',
    //                 hosp_Id: '',
    //                 dept_Id: '',
    //                 doctor_Intro: '',
    //                 fee_Recommend: 0,
    //                 fee_Diag: 0,
    //                 fee_Solution: 0,
    //                 cost_Surgery: 0,
    //                 fee_Surgery: 0
    //             }
    //         }
    //
    //         $scope.page = {
    //             totalItems: 0,
    //             currentPage: 1,
    //             currentItems: 0,
    //             maxSize: 5,				//max size of pagination
    //             itemsPerPage: 10
    //         }
    //
    //         $scope.getActivityList = function () {
    //             var params = {
    //                 userId: $scope.user.userId,
    //                 pageNo: 1,
    //                 pageSize: 10
    //             };
    //             RESTService.getResponse("/rest/useractivity/getUserActivityList?" + $.param(params)).then(function (response) {
    //                 $scope.activityList = response;
    //             });
    //         }
    //
    //         $scope.getActivityList();
    //
    //         function User(item) {
    //             var user = {
    //                 userId: item.userId,
    //                 realName: item.realName,
    //                 mobile_Phone: item.mobile_Phone,
    //                 email: item.email,
    //                 icCardFile: item.icCardFile,
    //                 icNo: item.icNo,
    //                 gender: item.gender,
    //                 race_Id: item.race_Id,
    //                 age: item.age,
    //                 location_Country: item.location_Country,
    //                 location_Province: item.location_Province,
    //                 location_City: item.location_City,
    //                 location_County: item.location_County,
    //                 location_Town: item.location_Town,
    //                 location_Address: item.location_Address,
    //                 marriage: item.marriage,
    //                 telephone: item.telephone,
    //                 emerg_Contact: item.emerg_Contact,
    //                 emerg_Contact_Mobile: item.emerg_Contact_Mobile,
    //                 photo_File: item.photo_File
    //             };
    //             return user;
    //         };
    //         function Doctor(item) {
    //             var doctor = {
    //                 userId: item.userId,
    //                 doctQuali_Id: item.doctQuali_Id,
    //                 hosp_Id: item.hosp_Id,
    //                 dept_Id: item.dept_Id,
    //                 doctor_Intro: item.doctor_Intro,
    //                 fee_Recommend: item.fee_Recommend,
    //                 fee_Diag: item.fee_Diag,
    //                 fee_Solution: item.fee_Solution,
    //                 cost_Surgery: item.cost_Surgery,
    //                 fee_Surgery: item.fee_Surgery
    //             };
    //             return doctor;
    //         };
    //
    //         //获取好友列表
    //         $scope.isFriend = false;
    //         $scope.userId = $scope.user.userId;
    //         RESTService.getResponse("/rest/chat/getChats?").then(function(response){
    //             $scope.userIdList = [];
    //             angular.forEach(response,function(value){
    //                 $scope.userIdList.push(value.userId);
    //             });
    //             if(!Array.value){
    //                 if($.inArray($scope.userId,$scope.userIdList) < 0){
    //                     $scope.isFriend = true;
    //                 }
    //             }
    //             return $scope.isFriend;
    //         });
    //
    //         //加好友
    //         $scope.addFriends = function(userId){
    //             $scope.friendId = userId;
    //             var url = '/rest/chat/createChatMessageAddingFriend?';
    //             RESTService.postResponse(url,{friendId:$scope.friendId})
    //                 .then(function(response){
    //                     console.log(JSON.stringify(response),'kkkkkkkkkkk');
    //                 });
    //             $scope.cancel();
    //         };
    //     }]);


//app.controller("viewreportCtrl", ["$scope", "$modal", "$timeout", "RESTService", "ModeShapeService", "AuthService", "$stateParams",
//	function($scope,   $modal,   $timeout,   RESTService, ModeShapeService, AuthService, $stateParams) {
//
//		$scope.service_Id = $stateParams.service_Id;
//		$scope.servReq_Id = $stateParams.servReq_Id;
//
//		var loadViewReportData = function() {
//
//			// get service type
//			RESTService.getResponse(URL2.service.getServiceType + "service_Id=" + $scope.service_Id ).then(function(response) {
//				$scope.serviceType = response[0];
//			});
//			RESTService.getResponse(URL2.servreq.getServReq.format($scope.servReq_Id)).then(
//				function(response) {
//					$scope.servReq = response[0];
//				});
//			RESTService.getResponse(URL2.patient.getPatients + "status=" + $scope.status + "&like=" + $scope.like
//				+ "&pageNo=" + $scope.page.currentPage +"&pageSize="+ $scope.page.itemsPerPage)
//				.then(function(response){
//					$scope.patients = response;
//				})
//		};
//
//		$scope.init = function() {
//			loadViewReportData();
//		};
//
//		//3 open modal
//		$scope.open = function(attrs, model) {
//			//model.scope = $scope;
//			var modalInstance = $modal.open(angular.extend({
//				controller: "ModalInstanceCtrl",
//				resolve: {
//					items: function() {
//						return [Object(model)];
//					}
//				}
//			}, attrs));
//		};
//
//	}]);
})();